package com.epam.cdp.selenium2.core.ui;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.epam.cdp.selenium2.core.configuration.GlobalConfiguration;
import com.epam.cdp.selenium2.core.configuration.SeleniumInstanceConfiguration;

/**
 * @author yyudzitski
 */
public class Browser
{
  private static final String SERVER_URL_TEMPLATE = "http://%1$s:%2$s/wd/hub";

  private static WebDriver currentDriver;

  private static WebDriverBackedSelenium selenium;

  private Browser()
  {
    /** Nothing to do */
  }

  private static URL buildServerUrl( SeleniumInstanceConfiguration config ) throws MalformedURLException
  {
    URL serverUrl = new URL( String.format( SERVER_URL_TEMPLATE, config.getSeleniumHost(), config.getSeleniumPort() ) );
    return serverUrl;
  }
  
  private static DesiredCapabilities buildCapabilities(SeleniumInstanceConfiguration seleniumConfig)
  {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setBrowserName( seleniumConfig.getDriverType().toString() );
    capabilities.setPlatform( Platform.WINDOWS );
    capabilities.setJavascriptEnabled( true );
    return capabilities;
  }

  public static WebDriver getBrowser()
  {
    if( currentDriver != null )
    {
      return currentDriver;
    }
    return getBrowser( GlobalConfiguration.getInstance().getSeleniumConfiguration().getDefaultConfiguration() );
  }

  public static WebDriver getBrowser( SeleniumInstanceConfiguration seleniumConfig )
  {
    URL serverUrl = null;
    try
    {
      serverUrl = buildServerUrl( seleniumConfig );
    }
    catch( MalformedURLException e )
    {
      throw new RuntimeException( e.getMessage() );
    }
    DesiredCapabilities capabilities = buildCapabilities( seleniumConfig );
    currentDriver = new RemoteWebDriver( serverUrl, capabilities );
    selenium = new WebDriverBackedSelenium( currentDriver, serverUrl.toString() );
    return currentDriver;
  }

  public static boolean isTextPresent( String pattern )
  {
    return selenium.isTextPresent( pattern );
  }

  public static void terminate()
  {
    if( currentDriver != null )
    {
      currentDriver.close();
    }
    if( selenium != null )
    {
      selenium.stop();
    }
  }
}